<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="合同名称:">
        <el-input v-model="query.templateName" placeholder="请选择" clearable />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.templateStatus">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <bargain-info ref="bargainInfo" :tree-data="treeData" />
    <audit-info ref="auditInfo" :tree-data="treeData" />
    <not-info ref="notInfo" :tree-data="treeData" />
    <can-info ref="canInfo" :tree-data="treeData" />
    <pact-info ref="pactInfo" />
  </div>
</template>

<script>
  import {
    queryContractManageList,
    queryEableContract,
    queryMap
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { parseTime } from '@/utils'
  import BargainInfo from './components/BargainInfo.vue'
  import AuditInfo from './components/AuditInfo.vue'
  import NotInfo from './components/NotInfo'
  import CanInfo from './components/CanInfo'
  import PactInfo from './components/PactInfo.vue'

  export default {
    name: 'tab-info',
    components: {
      BargainInfo,
      AuditInfo,
      NotInfo,
      CanInfo,
      PactInfo
    },
    data() {
      return {
        treeData: [],
        csmTypeMap: [],
        query: {
          templateName: '',
          templateStatus: 1
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'templateId',
              label: '编号'
            },
            {
              prop: 'templateName',
              width: 160,
              label: '合同名称'
            },
            {
              prop: 'createTime',
              label: '创建日期',
              width: 180,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'createUser',
              label: '创建人'
            },
            {
              prop: 'suitableRange',
              label: '适用范围',
              render: (h, { row }) => <span>{ row.suitableRange && this.suitableRangeFormat(row.suitableRange) }</span>
            },
            {
              prop: 'validPeriod',
              label: '有效期',
              render: (h, { row }) => <span>{ row.validPeriod === 1 ? '一年' : '永久' }</span>
            },
            {
              prop: 'signedCount',
              label: '已签订',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.showSignedListWin(row)}>{row.signedCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'waitCheckCount',
              label: '待审核',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.showWaitCheckListWin(row)}>{row.waitCheckCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'notSignedCount',
              label: '未签订',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.showNotSignedListWin(row)}>{row.notSignedCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'invalidCount',
              label: '已作废',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.showInvalidListWin(row)}>{row.invalidCount}</el-link>
                  </div>
                )
              }
            },
            {
              prop: 'templateStatus',
              label: '状态',
              render: (h, { row }) => <span>{ row.templateStatus === 1 ? '启用' : '禁用' }</span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 100,
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.use(row)}>启/禁用</el-link>
                    <el-link size='mini' onClick={() => this.openDetail(row)}>详情</el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this.query,
          currentPage,
          pageSize
        }
        const res = await queryContractManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await queryMap({ enumName: 'CustomerType' })
        this.csmTypeMap = res.data // 状态
      },
      // 启/禁用
      async use(row) {
        let title = '启用'
        if (row.templateStatus === 1) title = '禁用'
        this.$confirm(`确认要${title}"${row.templateName}"吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在执行操作',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          this.$refs.lbTable.fetch({ currentPage: 1 })
          queryEableContract({ templateId: row.templateId, templateStatus: row.templateStatus === 1 ? 2 : 1 }).then(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
            this.$notify({
              title: '提示',
              message: `${title}成功`,
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 详情
      openDetail(row) {
        this.$refs.pactInfo.open(row)
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 已签订
      showSignedListWin(row) {
        this.$refs.bargainInfo.open(row)
      },
      // 待审核
      showWaitCheckListWin(row) {
        this.$refs.auditInfo.open(row)
      },
      // 未签订
      showNotSignedListWin(row) {
        this.$refs.notInfo.open(row)
      },
      // 已作废
      showInvalidListWin(row) {
        this.$refs.canInfo.open(row)
      },
      // 适用范围
      suitableRangeFormat(val, row) {
        var arr = []
        if ((val >> 0) & 0x01 > 0) {
          arr.push('居民用户')
        }
        if ((val >> 1) & 0x01 > 0) {
          arr.push('非居民用户')
        }
        if ((val >> 2) & 0x01 > 0) {
          arr.push('工业用户')
        }
        if ((val >> 3) & 0x01 > 0) {
          arr.push('瓶批用户')
        }
        if ((val >> 4) & 0x01 > 0) {
          arr.push('槽批用户')
        }
        return arr.join(',')
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style scoped>

</style>
